package algo.LocalSearch;

import algo.Model.*;

import java.util.Iterator;
import java.util.HashSet;
import java.util.Iterator;

public class FuncPlus extends BasicLocalSearchEntity implements IFunction {
	//LocalSolver	_ls;
	
	IFunction _f1;
	IFunction _f2;
	VarInt[]	_x;
	BasicLocalSearchEntity[]	_e;
	int		_value;
	boolean	_posted;
	
	public FuncPlus(IFunction f1, IFunction f2){
		_f1 = f1; _f2 = f2;
		setLocalSolver(f1.getLocalSolver());
		post();
	}
	//public LocalSolver getLocalSolver(){
		//return _ls;
	//}
	public FuncPlus(VarInt x, VarInt y){
		_f1 = new FuncVarConst(x);
		_f2 = new FuncVarConst(y);
		setLocalSolver(_f1.getLocalSolver());
		post();
	}
	
	public BasicLocalSearchEntity[] getDependEntities(){
		return _e;
	}
	
	public String name(){
		return "FuncPlus[" + getID() + "]";
	}
	void post(){
		_e = new BasicLocalSearchEntity[2];
		_e[0] = (BasicLocalSearchEntity)_f1;
		_e[1] = (BasicLocalSearchEntity)_f2;
		VarInt[] x1 = _f1.getVariables();
		VarInt[] x2 = _f2.getVariables();
		HashSet<VarInt> S = new HashSet<VarInt>();
		if(x1 != null) 
			for(int i = 0; i < x1.length; i++)
				S.add(x1[i]);
		if(x2 != null)
			for(int i = 0; i < x2.length; i++)
				S.add(x2[i]);
		_x = new VarInt[S.size()];
		int i = -1;
		Iterator it = S.iterator();
		while(it.hasNext()){
			VarInt xi = (VarInt)it.next();
			i++;
			_x[i] = xi;
		}
		LocalSolver _ls = getLocalSolver();
		_ls.post(this);
	}
	public VarInt[] getVariables(){
		return _x;
	}
	@Override
	public int getValue() {
		// TODO Auto-generated method stub
		return _value;
	}

	@Override
	public int getAssignDelta(VarInt x, int val) {
		// TODO Auto-generated method stub
		return _f1.getAssignDelta(x, val) + _f2.getAssignDelta(x, val);
	}

	@Override
	public void propagateInt(VarInt x, int val) {
		// TODO Auto-generated method stub
		//_f1.propagate(x, val);
		//_f2.propagate(x, val);
		_value = _f1.getValue() + _f2.getValue();
		//System.out.println("FuncPlus::propagate(" + x.name() + "," + val + ") -> value = " + getValue());
	}

	@Override
	public void initPropagate() {
		// TODO Auto-generated method stub
		//_f1.initPropagate();
		//_f2.initPropagate();
		//System.out.println("FuncPlus::initPropagate");
		_value = _f1.getValue() + _f2.getValue();
		//System.out.println("FuncPlus::initPropagate, value = " + _value);
	}

	@Override
	public boolean verify() {
		// TODO Auto-generated method stub
		return true;
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}
